var zTreeObjInMAD ;
var lastValueInMAD = "" , nodeListInMAD = [] ;
$(function() {

    getAllMdcInDo();
    clickMdcInDo("MDCA","mdc") ;
    $("#"+tabId+" #word").bind("focus", focusKeyInMAD)
        .bind("blur", blurKeyInMAD)
        .bind("propertychange", searchNodeInMAD)
        .bind("input", searchNodeInMAD);

	/**
	 * 按回车查询
	 */
	$("#"+tabId+" #word").keydown(function(ev) {
		if (ev.keyCode == 13) {
			$('#s-btn').click();
		}
	});
	
    //给超链接导出按钮添加点击事件
    $("#"+tabId+" .panel-heading").on( 'click', '#mdcTreeExport', function () {
    	var treeNodes = zTreeObjInMAD.getNodes();
    	var tableNodes=[];
    	var exportTable;
    	if(treeNodes && treeNodes.length>0){//如果一级菜单有数据
    		$.each(treeNodes,function(i,treeNode0){
    			if(treeNode0 && treeNode0['id'] && treeNode0['name'] ){
    				tableNodes.push({'id':treeNode0['id'],'name':treeNode0['name'],'pid':treeNode0['pid']});
    			}
    			//如果二级菜单有数据
    			if(treeNode0 && treeNode0.children && treeNode0.children.length >0){
    				$.each(treeNode0.children,function(i,treeNode1){
    	    			if(treeNode1 && treeNode1['id'] && treeNode1['name'] ){
    	    				tableNodes.push({'id':treeNode1['id'],'name':'——'+treeNode1['name'],'pid':treeNode1['pid']});
    	    			}
    	    			//如果三级菜单有数据
    	    			if(treeNode1 && treeNode1.children && treeNode1.children.length >0){
    	    				$.each(treeNode1.children,function(i,treeNode2){
    	    	    			if(treeNode2 && treeNode2['id'] && treeNode2['name'] ){
    	    	    				tableNodes.push({'id':treeNode2['id'],'name':'—— ——'+treeNode2['name'],'pid':treeNode2['pid']});
    	    	    			}
    	    				});
    	    			}
    				});
    			}
    		});
    	}
    	//如果数据不为空则开始画表
    	if(tableNodes && tableNodes.length >0){
            //ajax加载动画 '0':去掉 ， '1':添加
    		drgUI.bindAjaxStart('0');//去掉ajax加载动画
    		$.post(contextPath+"/pages/common/top-dialog-buttons.jsp").done(function(data){
    			var dialog  = $(data);
    			dialog.find(".modal-title").html('病组导出');
    			dialog.find(".modal-dialog").css('width','700');
    			//加载动画
    			dialog.find("#echartcq4 img").css('width','660').css('height','300');
    			dialog.find(".modal-body").css('width','680');
    			dialog.modal({               // modal():调用模式窗口
    				keyboard : true      //当按下 escape 键时关闭模态框，设置为 false 时则按键无效
    			}).on({
    				//当模态框完全对用户隐藏时触发。
    				"hidden.bs.modal" : function() {
    					dialog.remove();
    				},
    				//当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
    	            "shown.bs.modal" : function(){
    	    				var str = '';
    	    				str+=' <div class="row-fluid clearfix">  ';
    	    				str+=' 		<div class="col-sm-12">  ';
    	    				str+='			<div style="width:99%;"><table id="mdcTreeExportTable" width="100%" class="cell-border"></table></div>';
    	    				str+=' 		</div>';
    	    				str+=' </div>';
    	    				dialog.find(".modal-body").html(str);
    	    		    	var tableData = tableNodes ? tableNodes:[];
    	    		    	//表格信息 	
    	    				var paramsTables={
    	    					searching: true, //此选项用来开启、关闭Datatables的搜索功能
    	    					lengthChange: false, //是否允许最终用户改变表格每页显示的记录数
    	    					paging: true,  //是否开启本地分页
    	    					info:true,     //控制是否显示表格左下角的信息
    	    					ordering:false, //是否允许Datatables开启排序
//    	    					autoWidth:true, //控制Datatables是否自适应宽度
    	    					scrollX:true,
    	    					scrollY: false //当表格高度超过300px的时候，显示垂直滚动条
    	    				};
    	    				var columns=[
    	    		               {"title":"名称","data":"name","width":"70%"},
    	    		               {"title":"编码","data":"id","width":"15%"},
    	    		               {"title":"父级编码","data":"pid","width":"15%"}
    	    			     ];
    	    				exportTable = dialog.find("#mdcTreeExportTable").dataTableBasic(columns, tableData,paramsTables);
    	    				$(".modal-footer").hide();
    	            }//"shown.bs.modal" : function(){
    			});//end on
    		});//$.post()
    	}
    	return false;
    } );

});

/**
 * 单击mdc列表事件
 */
function clickMdcInDo(code,type) {
    var currentCheckdType = "" ;
	// 显示第一个MDC的ADRG
	$.post(contextPath + "/diaAndOperInDRGController/findDiaAndOpeByMdc.dhc", {
				'code' : code,
				'type' : type
			}, function(result) {
				var checkBox = "<div><div id=\"DOType\">\n" +
                    "<input type=\"checkbox\" class=\"form-control\" name=\"typeName\" value=\"D\" >诊断 &nbsp; " +
					 "<input type=\"checkbox\" class=\"form-control\" name=\"typeName\" value=\"O\" >手术 &nbsp; " +
					 "          </div></div> ";
				var columns=[
					{
						"data":"code","title":"编码","width":"25%"
					},
					{
						"data":"desc","title":"描述","width":"55%"
					},
					{
						"data":"tp","title":checkBox,"width":"20%"
					}
				];

				var paramsDataTables={searching:true,lengthChange:false,info:true,ordering:false,paging:false,scrollX:true,scrollY:'350px',autoWidth:false};
				paramsDataTables.drawCallback = function(){
                    $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead #DOType input').iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square-blue',
                        increaseArea: '20%' // optional
                    });

                    if(currentCheckdType == "") {
                        $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead input[name="typeName"][value="D"]').iCheck('check');
                        $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead input[name="typeName"][value="O"]').iCheck('check');
                    } else {
                        $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead input[name="typeName"][value="'+currentCheckdType+'"]').iCheck('check');
                    }

                    var changeFlag = true ;
                    $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead #DOType input').on('ifChanged', function(event){
                        currentCheckdType = "" ;
                        $('#'+tabId+' #diaAndOpeTable_wrapper .dataTables_scrollHead input:checkbox[name="typeName"]:checked').each(function(){
                            currentCheckdType+=$(this).val();
                        });
                        // 至少选中一个
                        if(currentCheckdType == "") {
                            $(this).iCheck('check');
                            return ;
                        }
                        var wd = "" ;
                        if(currentCheckdType == "D"){
                            wd = "诊断"
                        } else if (currentCheckdType == "O") {
                            wd = "手术"
                        }
                        $("#"+tabId+" #tabTitle").text( code+"下的主要诊断和主要手术") ;
                        $("#"+tabId+" #diaAndOpeTable").DataTable().column( 2 ).search(
                            wd,false,true
                        ).draw();
                    });
				} ;
				//<h5 align="center">全院各科室组DRG得分比较汇总表</h5>
				$("#"+tabId+" #tabTitle").text( code+"下的主要诊断和主要手术") ;
        		$("#"+tabId+" #diaAndOpeTable").dataTableBasic(columns, result.data,paramsDataTables);
    });
}


/**
 *@Description: 聚焦
 *@Param: 
 *@return: 
 *@Author: chenhanlin
 *@date: 2019/1/6
 */
function focusKeyInMAD(e) {
    if ($("#"+tabId+" #word").hasClass("empty")) {
        $("#"+tabId+" #word").removeClass("empty");
    }
}
/**
 *@Description: 失去焦点
 *@Param: 
 *@return: 
 *@Author: chenhanlin
 *@date: 2019/1/6
 */
function blurKeyInMAD(e) {
    if ($("#"+tabId+" #word").get(0).value === "") {
        $("#"+tabId+" #word").addClass("empty");
    }
}
//  搜索
function searchNodeInMAD(e) {
    var value = $.trim($("#"+tabId+" #word").get(0).value);
    var keyType = "name";
    if ($("#"+tabId+" #word").hasClass("empty")) {
        value = "";
    }
    if (lastValueInMAD === value) return;
    lastValueInMAD = value ;
    updateNodes(false);
    nodeListInMAD = zTreeObjInMAD.getNodesByParamFuzzy(keyType, value);
    if (value == "" || nodeListInMAD.length == 0 ) {
        zTreeObjInMAD.expandAll(false);
        return;
    }
    updateNodes(true);
}
// 更新节点高亮状态
function updateNodes(highlight) {
    for( var i=0, l=nodeListInMAD.length; i<l; i++) {
        nodeListInMAD[i].highlight = highlight;
        zTreeObjInMAD.updateNode(nodeListInMAD[i]);
        // 展开搜索到的节点的父节点
        // 设置focus = true 表示 展开 / 折叠 操作后，通过设置焦点保证此焦点进入可视区域内
        var focus = false ;
        if( i == 0 && highlight ) {
            focus = true ;
        }
        zTreeObjInMAD.expandNode(nodeListInMAD[i].getParentNode(),highlight,focus,false);
    }
}




/**
 *@Description: DRG Tree初始化
 *@Param:
 *@return:
 *@Author: chenhanlin
 *@date: 2019/1/5
 */
function getAllMdcInDo() {
    $.post(contextPath + "/diaAndOperInDRGController/constructMdcAdrgDrg.dhc", {"verCode":sysConfig.GROUP_VER,"stdType":groupMatchStd[sysConfig.GROUP_VER]}, function(result) {
        var ztreeNode = result.data ;
        var fontCss = {};
        var setting = {
            data:{
                simpleData:{
                    enable: true,
                    idKey:  "id",
                    pIdKey: "pid",
                    rootPId:"0"
                }
            },
            view :{
                showIcon: false,
                fontCss: getFontCss
            },
            callback: {
                onClick: zTreeOnClick
            }
        };

        function zTreeOnClick(event, treeId, treeNode) {
            var type ;
            var code = treeNode.id ;
            if(treeNode.level == 0) {
                type = "mdc" ;
            } else if(treeNode.level == 1) {
                type = "adrg" ;
            } else {
                type = "drg" ;
            }
            clickMdcInDo(code,type) ;

        }

        function getFontCss(treeId, treeNode) {
            return (!!treeNode.highlight) ? {color:"#6633FF", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
        }
        zTreeObjInMAD = $.fn.zTree.init($("#"+tabId+" #drgTree"),setting,ztreeNode);

    });

}
